<template>
  <a-spin :spinning="confirmLoading" style="background: #fff">
    <j-form-container :disabled="false">
      <a-form-model ref="form" :model="model" :rules="validatorRules" slot="detail">
        <a-row :gutter="48">
          <a-col :span="8">
            <a-form-model-item label="单据编号" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="purchaseBill">
              <a-input v-model="model.purchaseBill" placeholder="请输入单据编号" disabled></a-input>
            </a-form-model-item>
          </a-col>
          <a-col :span="8">
            <a-form-model-item label="申请人" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="proposer">
              <select-user-by-dep
                placeholder="请选择申请人"
                v-model="model.proposer" disabled/>
            </a-form-model-item>
          </a-col>
          <a-col :span="8">
            <a-form-model-item label="申请部门" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="departId">
              <j-select-depart placeholder="请选择申请部门" v-model="model.departId" disabled/>
            </a-form-model-item>
          </a-col>
          <a-col :span="8">
            <a-form-model-item label="申请时间" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="createTime">
              <j-date
                placeholder="请选择申请时间"
                v-model="model.createTime"
                :show-time="true"
                date-format="YYYY-MM-DD HH:mm:ss"
                style="width: 100%"
                disabled/>
            </a-form-model-item>
          </a-col>
        </a-row>
        <a-divider>作废信息</a-divider>
        <a-collapse v-model="activeKey">
          <!-- 基本信息 -->
          <a-collapse-panel key="1" header="基本信息">
            <a-row :gutter="48">
              <a-col :span="8">
                <a-form-model-item label="单据名称" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="purchaseBillId">
                  <SelectPurchaseApplyInput :disabled="formDisabled" v-model="model.purchaseBillId" placeholder="请选择招标采购申请表单" @back="purchaseInfoBack"/>
                </a-form-model-item>
              </a-col>
              <a-col :span="8" :hidden="true">
                <a-form-model-item label="标题" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="bpmBizTitle">
                  <a-input :disabled="showdetailDisabled" v-model="model.bpmBizTitle" placeholder="请输入标题" ></a-input>
                </a-form-model-item>
              </a-col>
              <!-- <a-col :span="8">
                <a-form-model-item label="单据编号" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="invalidationPurchaseBill">
                  <a-input v-model="model.invalidationPurchaseBill" placeholder="请输入单据编号" disabled></a-input>
                </a-form-model-item>
              </a-col> -->
              <a-col :span="8">
                <a-form-model-item label="申请人" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="invalidationProposer">
                  <select-user-by-dep
                    placeholder="请选择申请人"
                    v-model="model.invalidationProposer" disabled/>
                </a-form-model-item>
              </a-col>
              <a-col :span="8">
                <a-form-model-item label="申请部门" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="invalidationDepartId">
                  <j-select-depart placeholder="请选择申请部门" v-model="model.invalidationDepartId" disabled/>
                </a-form-model-item>
              </a-col>
              <a-col :span="8">
                <a-form-model-item label="申请时间" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="invalidationCreateTime">
                  <j-date
                    placeholder="请选择申请时间"
                    v-model="model.invalidationCreateTime"
                    :show-time="true"
                    date-format="YYYY-MM-DD HH:mm:ss"
                    style="width: 100%"
                    disabled/>
                </a-form-model-item>
              </a-col>
              <a-col :span="8" v-if="!showdetailDisabled">
                <a-form-model-item label="关联项目" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="projectId">
                  <select-project-input v-model="model.projectId" placeholder="请选择关联项目" :disabled="showdetailDisabled" />
                </a-form-model-item>
              </a-col>
              <a-col :span="8" v-else>
                <a-form-model-item label="关联项目" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="projectId">
                  <a-input :readOnly="true" :disabled="!model.projectId_dictText" v-model="model.projectId_dictText" style="color: #1890FF;" placeholder="请选择关联项目" @click.prevent="projectClick(model.projectId)"></a-input>
                </a-form-model-item>
              </a-col>
              <a-col :span="8">
                <a-form-model-item label="采购总预算（元）" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="projectBudget">
                  <a-input-number :max="99999999" :min="0" :precision="2" v-model="model.projectBudget" placeholder="请输入采购总预算" style="width: 100%" disabled/>
                </a-form-model-item>
              </a-col>
              <a-col :span="8">
                <a-form-model-item label="费用所属团队" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="teamId">
                  <select-team-input placeholder="请选择团队" :disabled="showdetailDisabled" v-model="model.teamId" :tdlx="3" />
                </a-form-model-item>
              </a-col>
              <a-col :span="8">
                <a-form-model-item label="付款方式" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="payManner">
                  <a-input :disabled="showdetailDisabled" :max-length="100" v-model="model.payManner" placeholder="请输入付款方式" />
                </a-form-model-item>
              </a-col>
              <a-col :span="8">
                <a-form-model-item label="采购大类" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="provisionBroad">
                  <a-select
                    v-model="model.provisionBroad"
                    :disabled="showdetailDisabled"
                    placeholder="请选择采购大类"
                    :showSearch="true"
                    :allowClear="true"
                    :filterOption="filterOption"
                    @change="handleChange"
                    :getPopupContainer="triggerNode => {return triggerNode.parentNode}"
                  >
                    <a-select-option v-for="item in provisionBroadList" :key="item.id" :value="item.id">{{ item.categoryName }}</a-select-option>
                  </a-select>
                </a-form-model-item>
              </a-col>
              <a-col :span="8">
                <a-form-model-item label="采购方式" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="invitationManner">
                  <j-dict-select-tag :disabled="showdetailDisabled" type="list" v-model="model.invitationManner" dictCode="bidding_type" placeholder="请选择货到付款" />
                </a-form-model-item>
              </a-col>
              <a-col :span="8" v-if="showBusinessSegment">
                <a-form-model-item label="所属业务板块" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="businessSegment">
                  <j-dict-select-tag :disabled="showdetailDisabled" type="list" v-model="model.businessSegment" dictCode="business_segment" placeholder="请选择所属业务板块" />
                </a-form-model-item>
              </a-col>
              <a-col :span="8">
                <a-form-model-item label="期望到货时间" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="expectUseTime">
                  <j-date
                    :disabled="showdetailDisabled"
                    placeholder="请选择到货时间"
                    v-model="model.expectUseTime"
                    :show-time="true"
                    date-format="YYYY-MM-DD HH:mm"
                    style="width: 100%"
                  />
                </a-form-model-item>
              </a-col>
              <a-col :span="24">
                <a-form-model-item label="采购需求及项目描述" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="description">
                  <a-input :disabled="showdetailDisabled" :max-length="30" v-model="model.description" placeholder="请输入采购需求及项目描述" ></a-input>
                </a-form-model-item>
              </a-col>
              <a-col :span="24">
                <a-form-model-item label="备注" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="remark">
                  <a-textarea :disabled="showdetailDisabled" :max-length="500" v-model="model.remark" rows="4" placeholder="请输入备注"/>
                </a-form-model-item>
              </a-col>
            </a-row>
          </a-collapse-panel>

          <!-- 物料明细 -->
          <a-collapse-panel key="2" header="物料明细">
            <a-row :gutter="48">
              <ErpPurchaseApplyInvitationDetailList ref="purchaseApply" :disabled="showdetailDisabled" :provisionBroad="model.provisionBroad" @applyDetailData="applyDetailData" />
            </a-row>
          </a-collapse-panel>

          <!-- 附件信息 -->
          <a-collapse-panel key="3" header="附件信息（附件要求：1、业主盖章版合同；2、工程量清单；3、技术要求等）">
            <a-row :gutter="48">
              <a-col :span="24">
                <a-form-model-item prop="purchaseFile">
                  <j-upload v-if="!showdetailDisabled" :disabled="showdetailDisabled" v-model="model.purchaseFile"></j-upload>
                  <a-button v-else icon="download" @click="viewFile(model.purchaseFile)">文件列表</a-button>
                </a-form-model-item>
              </a-col>
            </a-row>
          </a-collapse-panel>
        </a-collapse>
        <a-row :gutter="48">
          <a-col :span="24">
            <a-form-model-item label="作废理由" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="invalidationReason">
              <a-textarea :max-length="500" :disabled="formDisabled" v-model="model.invalidationReason" rows="4" placeholder="请输入作废理由"/>
            </a-form-model-item>
          </a-col>
        </a-row>
      </a-form-model>
      <common-flow-list v-if="formBpm && model.bpmStatus !== '1'" :formData="formData" style="margin-top: 10px"></common-flow-list>
      <view-file-modal ref="viewFileModal"></view-file-modal>
    </j-form-container>
    <a-row :gutter="48">
      <a-col :span="24" style="text-align: center;margin-top: 15px">
        <a-button type="primary" v-if="formBpm" :style="{ marginRight: showFlowSubmitButton?'10px':'0px' }" @click="onPrint">打印</a-button>
        <a-button @click="submitForm('submit')" v-if="showFlowSubmitButton">提 交</a-button>
      </a-col>
    </a-row>
    <!-- 详情开始 -->
    <erp-project-report-modal  ref="projectForm"></erp-project-report-modal>
    <!-- 详情结束 -->
    <ErpPurchaseApplyInvitationFormPrint v-if="formBpm" class="print_style" id="applyinvitationContent" :formData="model" :formDataHistory="formData"></ErpPurchaseApplyInvitationFormPrint>
  </a-spin>
</template>

<script>

import { getAction, httpAction } from '@/api/manage'
import { viewFile } from '@/utils/util'
import ViewFileModal from '@/views/scy/components/ViewFileModal'
import { mapGetters } from 'vuex';
import moment from 'moment';
import SelectUserByDep from '@/views/scy/components/SelectUserByDep'
import SelectTeamInput from '@/views/scy/components/SelectTeamInput'
import ErpPurchaseApplyInvitationDetailList from './reference/ErpPurchaseApplyInvitationDetailList';
import SelectProjectInput from '@/views/scy/components/SelectProjectInput'
import CommonFlowList from '@/views/components/CommonFlowList.vue';
import ErpProjectReportModal from '@/views/erp/report/project/modules/ErpProjectReportModal'
import Print from '@/utils/print/printarea.js';
import SelectPurchaseApplyInput from './SelectPurchaseApplyInput'
import ErpPurchaseApplyInvitationFormPrint from './ErpPurchaseApplyInvitationFormPrint.vue';
export default {
    name: 'erpPurchaseApplyInvitationForm',
    mixins: [viewFile],
    components: {
      ErpProjectReportModal,
      ViewFileModal,
      SelectTeamInput,
      SelectUserByDep,
      ErpPurchaseApplyInvitationDetailList,
      SelectProjectInput,
      CommonFlowList,
      SelectPurchaseApplyInput,
      ErpPurchaseApplyInvitationFormPrint
    },
    props: {
      // 流程表单data
      formData: {
        type: Object,
        default: () => {},
        required: false
      },
      // 表单模式：true流程表单 false普通表单
      formBpm: {
        type: Boolean,
        default: false,
        required: false
      },
      // 表单禁用
      disabled: {
        type: Boolean,
        default: false,
        required: false
      }
    },
    watch: {
      activeKey(key) {
        this.$forceUpdate()
      }
    },
    data () {
      return {
        userName: '',
        provisionBroadList: [], // 采购大类
        activeKey: ['1', '2', '3'],
        model: {
          purchaseBill: null,
          purchaseBillId: null,
          invalidationReason: ''
        },
        labelCol: {
        },
        wrapperCol: {
          xs: { span: 24 },
          sm: { span: 24 }
        },
        confirmLoading: false,
        validatorRules: {
          purchaseBillId: [
            { required: true, message: '请选择单据名称!', trigger: 'change' }
          ],
          invalidationReason: [
            { required: true, message: '请输入作废理由!', trigger: 'blur' },
          ],
        },
        url: {
          add: '/api/erp/purchase/procurement/erpPurchaseApplyInvitation/add',
          edit: '/api/erp/purchase/procurement/erpPurchaseApplyInvitation/edit',
          queryById: '/api/erp/purchase/procurement/erpPurchaseApplyInvitation/queryById',
          queryProvisionBroadList: '/api/erp/purchase/material/erpMaterialCategory/queryAllParent',
          gainBillNo: "/api/erp/purchase/procurement/erpPurchaseApplyInvitation/gainBillNo",
          queryByProjectId: '/api/erp/project/report/erpProjectReport/queryById',
          queryVerification: '/api/erp/purchase/procurement/erpPurchaseApplyInvitation/referencedVerification',
          queryVerificationCancelling: '/api/erp/purchase/procurement/erpPurchaseApplyInvitation/referencedVerificationCancelling',
        },
        details: [],
        provisionBroadups: null,
        showBusinessSegment: false,
        showdetailDisabled: true,
        purchaseBillIdBackups: null
      }
    },
    computed: {
      formDisabled() {
        if (this.formBpm === true) {
          if (this.formData.disabled === false) {
            return false
          }
          return true
        }
        return this.disabled
      },
      showFlowSubmitButton() {
        if (this.formBpm === true) {
          if (this.formData.disabled === false) {
            return true
          }
        }
        return false
      }
    },
    created () {
       // 备份model原始值
      this.modelDefault = JSON.parse(JSON.stringify(this.model));
      // 如果是流程中表单，则需要加载流程表单data
      this.showFlowData();
      this.findProvisionBroadList()
    },
    methods: {
      ...mapGetters(['userInfo']),
      purchaseInfoBack(item){
        const that = this
        //判断不为空
        if(!!this.model.purchaseBillId && item.length > 0){
          //判断公司是否变化
          if(this.purchaseBillIdBackups !== item[0].id) {
            getAction(this.url.queryVerification,{ id: item[0].id}).then(res => {
              if(res.result == "校验通过"){
                getAction(this.url.queryVerificationCancelling,{ id: item[0].id}).then(response => {
                  if(response.result == "校验通过"){
                    //确认后进行改变
                    that.purchaseBillIdBackups = item[0].id
                    that.handleModelData(item[0])
                    that.model.purchaseBillId = item[0].id
                  } else {
                    that.$message.warning(response.message)
                    that.model.purchaseBillId = that.purchaseBillIdBackups
                  }
                })
              } else {
                that.$message.warning(res.message)
                that.model.purchaseBillId = that.purchaseBillIdBackups
              }
            })
          }
        }
      },
      handleModelData(val){
        // 选择单据 处理原表单数据
        this.$set(this.model,'invalidationPurchaseBill',val.purchaseBill)
        this.$set(this.model,'invalidationProposer',val.proposer)
        this.$set(this.model,'invalidationDepartId',val.departId)
        this.$set(this.model,'invalidationCreateTime',val.createTime)
        this.$set(this.model,'bpmBizTitle','作废-'+ this.userName + '-' + this.model.purchaseBill)
        this.$set(this.model,'projectId',val.projectId)
        this.$set(this.model,'projectBudget',val.projectBudget)
        this.$set(this.model,'teamId',val.teamId)
        this.$set(this.model,'payManner',val.payManner)
        this.$set(this.model,'provisionBroad',val.provisionBroad)
        this.$set(this.model,'invitationManner',val.invitationManner)
        this.$set(this.model,'businessSegment',val.businessSegment)
        this.$set(this.model,'expectUseTime',val.expectUseTime)
        this.$set(this.model,'description',val.description)
        this.$set(this.model,'remark',val.remark)
        this.$set(this.model,'purchaseFile',val.purchaseFile)
        this.$refs.purchaseApply.loadData(1, this.model.id)
        if(!!this.model.provisionBroad&&this.model.provisionBroad=='1535176942946377729'){
          // 选择的是行政类
          this.showBusinessSegment = false;
        }else{
          // 选择的不是行政类
          this.showBusinessSegment = true;
        }
      },
      getBillNo () {
        const that = this
        getAction(this.url.gainBillNo,{ type: '2' }).then((res)=>{
          if(res.success){
            that.model.purchaseBill = res.result//单据编号
          }
        })
      },
      add () {
        this.$refs["form"].clearValidate();
        this.model = Object.assign({},{ 
          purchaseBill: '',
          purchaseBillId: '',
          invalidationReason: ''
        })
        this.purchaseBillIdBackups = null
        this.$refs.purchaseApply.dataSource = []
        this.userName = this.userInfo().empName;// 当前登录人名称
        this.model.proposer = this.userInfo().empId; // 当前登录人
        this.model.departId = this.userInfo().deptId; //当前登录人部门
        this.model.createTime = moment().format('YYYY-MM-DD HH:mm:ss');
        this.getBillNo() //获取单据编号
      },
      edit (record) {
        this.$refs["form"].clearValidate();
        this.model = Object.assign({}, record);
        if (this.model.id) {
          this.$refs.purchaseApply.loadData(1, this.model.id)
        } else {
          this.$refs.purchaseApply.dataSource = []
        }
        if(!!this.model.provisionBroad&&this.model.provisionBroad=='1535176942946377729'){
          // 选择的是行政类
          this.showBusinessSegment = false;
        }else{
          // 选择的不是行政类
          this.showBusinessSegment = true;
        }
        this.provisionBroadups = this.model.provisionBroad
        this.visible = true;
      },
      // 渲染流程表单数据
      showFlowData() {
        if (this.formBpm === true) {
          let params = { id: this.formData.dataId };
          getAction(this.url.queryById, params).then((res) => {
            if (res.success) {
              this.edit(res.result);
            }
          });
        }
      },
      submitForm(type) {
        const that = this;
        // if (type == 'draft') {
        //   // 代表保存草稿不做校验
        //   this.submit(type)
        // } else if (type == 'submit') {
          
        // } else {
        //   console.log('传参数，保存：draft，提交：submit')
        // }
        // let details = this.$refs.purchaseApply.submitForm()
        // if (!details.length > 0) {
        //   this.$message.warning('请添加物料明细信息！');
        //   this.$emit('unButtonDisable');
        //   return
        // }
        // // 判断数据有没有填写数量或者预算价格
        // var isAmount = details.some(item => !item.amount);
        // var isBudgetAmount = details.some(item => item.budgetAmount === '' || item.budgetAmount === null);
        // if (isAmount) {
        //   // 当为true说明有值领用数量没有填写
        //   this.$message.warning('请填写物料明细中的数量！');
        //   this.$emit('unButtonDisable');
        //   return false
        // }
        // if (isBudgetAmount) {
        //   // 当为true说明有值领用用途没有填写
        //   this.$message.warning('请填写物料明细中的预算价格！');
        //   this.$emit('unButtonDisable');
        //   return false
        // }
        // if (this.model.projectBudget < 10000) {
        //   this.$message.warning('当前采购总金额小于10000元，请走采购申请单！');
        //   this.$emit('unButtonDisable');
        //   return
        // }
        // 触发表单验证
        this.$refs.form.validate(valid => {
          if (valid) {
            that.submit(type)
          } else {
            that.$emit('unButtonDisable')
          }
        })
      },
      submit (type) {
        const that = this;
        that.confirmLoading = true;
        let httpurl = '';
        let method = '';
        if (!this.model.id) {
          httpurl += this.url.add;
          method = 'post';
        } else {
          httpurl += this.url.edit;
          method = 'put';
        }
        let details = this.$refs.purchaseApply.submitForm() || []
        this.model.detailList = details
        httpAction(httpurl, this.model, method).then((res) => {
          if (res.success) {
            that.$message.success(res.message);
            if (method == 'post') {
              that.model.id = res.result;
            }
            that.$emit('ok', type, that.model);
          } else {
            that.$message.warning(res.message);
            that.$emit('unButtonDisable');
          }
        }).catch((error) => {
          that.$emit('unButtonDisable', error);
        }).finally(() => {
          that.confirmLoading = false;
        })
      },

      // 采购大类
      filterOption(input, option) {
        return (
          option.componentOptions.children[0].text.toLowerCase().indexOf(input.toLowerCase()) >= 0
        );
      },
      handleChange(item) {
        //判断不为空
        if(!!this.model.provisionBroad && !!item) {
          //判断团队是否变化
          if(this.provisionBroadups !== item) {
            let details = this.$refs.purchaseApply.submitForm()
            if(details.length > 0) {
              const that = this;
              that.$confirm({
                title: "是否确认",
                content: "是否确认切换采购大类，此操作将会清空物料明细中已填写的所有信息？",
                onOk() {
                  //确认后进行改变
                  that.provisionBroadups = that.model.provisionBroad
                  //清空子表数据
                  that.$refs.purchaseApply.dataSource = []
                  that.$set(that.model,'projectBudget',null)
                  that.isHideBusinessSegment()
                },
                onCancel() {
                  that.model.provisionBroad = that.provisionBroadups
                }
              });
            } else {
              this.provisionBroadups = item
              this.isHideBusinessSegment()
            }
          }
        }
      },
      isHideBusinessSegment(){
          if(!!this.model.provisionBroad&&this.model.provisionBroad=='1535176942946377729'){
            // 选择的是行政类
            this.showBusinessSegment = false;
          }else{
            // 选择的不是行政类
            this.showBusinessSegment = true;
          }
          // 清空数据
          this.$set(this.model,'businessSegment',null)
      },
      findProvisionBroadList() {
        const that = this
        that.provisionBroadList = []
        getAction(this.url.queryProvisionBroadList).then(res => {
          if (res.success) {
            res.result.forEach((res) => {
              that.provisionBroadList.push({ 'id': res.id, 'categoryName': res.categoryName })
            })
          } else {
            that.$message.warning(res.message)
          }
        })
      },
      applyDetailData(data) {
        this.details = data
        if(this.details.length > 0) {
          let count = 0
          this.details.forEach((item, index) => {
            count = count + (item.amount * item.budgetAmount)
          })
          this.$set(this.model,'projectBudget',count)
        } else {
          this.$set(this.model,'projectBudget',null)
        }
      },
      projectClick(id) {
        const that = this
        this.$nextTick(() => {
          getAction(this.url.queryByProjectId, { id: id }).then((res) => {
            if (res.success) {
              const model = res.result
              that.$refs.projectForm.getDetail(model);
              that.$refs.projectForm.title = '项目一览表';
            }
          })
        })
      },

      // 点击打印
      onPrint () {
        let print = new Print({
          el: '#applyinvitationContent',
          popTitle: '招标采购申请详情 · 禾美环保',
          endCallback() {

          }
        })
      }
      // backUserInfo(data) {
      //   this.model.applicant = data[0].orgDepart;//申请人单位
      //   this.model.departId = data[0].departmentId;//申请人部门
      // }
    }
  }
</script>
<style>
  @import "../../../../../utils/print.css";
  .print_style{
  position: absolute;
  top: 0;
  z-index: -1111;
}
</style>